import {EyeOutlined} from '@ant-design/icons';
import {DragSortTable, ProColumnType} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProForm,
  ProFormText,
  ProFormTextArea,
  BetaSchemaForm,
  ProFormSwitch
} from '@ant-design/pro-components';
import {Card, Col, Form, message, Popconfirm, Row, Image, Button} from 'antd';
import type {FC} from 'react';
import {useState} from 'react';
import {batchSaveSetting, getSettingList} from './service';
import useStyles from './style.style';
import CustomImgUpload from '@/components/CustomImgUpload';
import CustomEditor from '@/components/CustomRichEditor';
import {useRequest} from '@umijs/max';

interface TableFormDateType {
  key: string;
  workId?: string;
  name?: string;
  department?: string;
  isNew?: boolean;
  editable?: boolean;
}

type InternalNamePath = (string | number)[];

interface ErrorField {
  name: InternalNamePath;
  errors: string[];
}

const AdvancedForm: FC<Record<string, any>> = () => {
  const {styles} = useStyles();
  const [form] = Form.useForm()
  const [companyBannerAddForm] = Form.useForm()
  const [companyCertificateAddForm] = Form.useForm()
  const [publicFilteringCriteriaAddForm] = Form.useForm()
  const [companyBannerEditForm] = Form.useForm()
  const [companyCertificateEditForm] = Form.useForm()
  const [publicFilteringCriteriaEditForm] = Form.useForm()
  const [, setError] = useState<ErrorField[]>([]);

  const {refresh} = useRequest(getSettingList, {
    onSuccess(data) {
      // console.log('data', data);

      const newVal: any = {}
      Object.keys(data).forEach((key) => {
        try {
          newVal[key] = JSON.parse(data[key]?.value || '')
        } catch (e) {
        }
      })

      form.setFieldsValue(newVal)
    },
  });

  const onFinish = async (values: Record<string, any>) => {
    const hide = message.loading('正在保存');

    try {
      const res = await batchSaveSetting(values);
      if (res.code === 0) {
        hide();
        message.success('保存成功，即将刷新');
        refresh()
        return true;
      } else {
        hide();
        message.error('保存失败，请重试');
        return false;
      }
    } catch (error) {
      hide();
      message.error('保存失败，请重试');
      return false;
    }

  };

  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };

  const companyBannerColumns: ProColumnType<TableFormDateType>[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      valueType: 'digit',
      initialValue: form.getFieldsValue()?.home_grid?.length + 1 || 0,
      width: 120,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '图片',
      dataIndex: 'image',
      key: 'image',
      renderFormItem() {
        return <CustomImgUpload style={{width: 300}}/>
      },
      render: (text: any, record: any) => {
        return record?.image?.url ? <Image width={50} preview={{
          mask: <EyeOutlined/>
        }} src={record?.image?.url}/> : '-'
      },
    },
    {
      title: '是否显示',
      dataIndex: 'isShow',
      key: 'isShow',
      valueType: 'switch',
      initialValue: true,
      fieldProps: {
        unCheckedChildren: '隐藏',
        checkedChildren: '显示'
      },
      // width: '40%',
    },
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      render: (_, record: TableFormDateType,) => {
        return [
          <BetaSchemaForm<any>
            key="eidit"
            layoutType={'ModalForm'}
            form={companyBannerEditForm}
            onFinish={async (values) => {
              const companyBanner = form.getFieldsValue()?.company?.banner || []
              const newCompanyBanner = companyBanner.map((item: any) => {
                if (record?.key === item?.key) {
                  // eslint-disable-next-line no-param-reassign
                  item = {
                    ...item,
                    ...values
                  }
                }
                return item
              })

              form.setFieldValue(['company', 'banner'], newCompanyBanner)
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: `编辑 ${record.name} 公司简介轮播`,
              width: "500px",
            }}
            trigger={<a
              key="eidit"
              onClick={() => {
                companyBannerEditForm.resetFields()
                companyBannerEditForm.setFieldsValue(record)
              }}
            >
              编辑
            </a>}
            columns={companyBannerColumns as any}
          />,
          <Popconfirm
            key="del"
            title="删除"
            description={<>
              <p>确认删除 <b>{record?.name}</b> ?</p>
            </>}
            onConfirm={async () => {
              const companyBanner = (form.getFieldsValue()?.company?.banner || [])?.filter((item: any) => {
                return item?.key !== record?.key
              })
              form.setFieldValue(['company', 'banner'], companyBanner)
              return true
            }}
            okText="是"
            cancelText="否"
          >
            <a
              key="del"
            >
              删除
            </a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const companyCertificateColumns: ProColumnType<TableFormDateType>[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      valueType: 'digit',
      initialValue: form.getFieldsValue()?.home_grid?.length + 1 || 0,
      width: 120,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '图片',
      dataIndex: 'image',
      key: 'image',
      renderFormItem() {
        return <CustomImgUpload style={{width: 300}}/>
      },
      render: (text: any, record: any) => {
        return record?.image?.url ? <Image width={50} preview={{
          mask: <EyeOutlined/>
        }} src={record?.image?.url}/> : '-'
      },
    },
    {
      title: '是否显示',
      dataIndex: 'isShow',
      key: 'isShow',
      valueType: 'switch',
      initialValue: true,
      fieldProps: {
        unCheckedChildren: '隐藏',
        checkedChildren: '显示'
      },
      // width: '40%',
    },
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      render: (_, record: TableFormDateType,) => {
        return [
          <BetaSchemaForm<any>
            key="eidit"
            layoutType={'ModalForm'}
            form={companyCertificateEditForm}
            onFinish={async (values) => {
              const companyCertificate = form.getFieldsValue()?.company?.certificate || []
              const newCompanyCertificate = companyCertificate.map((item: any) => {
                if (record?.key === item?.key) {
                  // eslint-disable-next-line no-param-reassign
                  item = {
                    ...item,
                    ...values
                  }
                }
                return item
              })

              form.setFieldValue(['company', 'certificate'], newCompanyCertificate)
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: `编辑 ${record.name} 公司简介轮播`,
              width: "500px",
            }}
            trigger={<a
              key="eidit"
              onClick={() => {
                companyCertificateEditForm.resetFields()
                companyCertificateEditForm.setFieldsValue(record)
              }}
            >
              编辑
            </a>}
            columns={companyCertificateColumns as any}
          />,
          <Popconfirm
            key="del"
            title="删除"
            description={<>
              <p>确认删除 <b>{record?.name}</b> ?</p>
            </>}
            onConfirm={async () => {
              const companyCertificate = (form.getFieldsValue()?.company?.certificate || [])?.filter((item: any) => {
                return item?.key !== record?.key
              })
              form.setFieldValue(['company', 'certificate'], companyCertificate)
              return true
            }}
            okText="是"
            cancelText="否"
          >
            <a
              key="del"
            >
              删除
            </a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const publicFilteringCriteriaColumns: ProColumnType<TableFormDateType>[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      valueType: 'digit',
      initialValue: form.getFieldsValue()?.home_grid?.length + 1 || 0,
      width: 120,
    },
    {
      title: '名称',
      dataIndex: 'title',
    },
    {
      title: '字段名',
      dataIndex: 'fieldName',
    },
    {
      title: '筛选类型',
      dataIndex: 'filterType',
      valueType: 'select',
      valueEnum: {
        range: {text: '范围筛选'},
        value: {text: '值筛选'}
      }
    },
    {
      title: '是否显示',
      dataIndex: 'isShow',
      valueType: 'switch',
      initialValue: true,
      fieldProps: {
        unCheckedChildren: '隐藏',
        checkedChildren: '显示'
      },
      // width: '40%',
    },
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      render: (_, record: TableFormDateType,) => {
        return [
          <BetaSchemaForm<any>
            key="eidit"
            layoutType={'ModalForm'}
            form={publicFilteringCriteriaEditForm}
            onFinish={async (values) => {
              const publicFilteringCriteria = form.getFieldsValue()?.publicFilteringCriteria || []
              const newPublicFilteringCriteria = publicFilteringCriteria.map((item: any) => {
                if (record?.key === item?.key) {
                  // eslint-disable-next-line no-param-reassign
                  item = {
                    ...item,
                    ...values
                  }
                }
                return item
              })

              form.setFieldValue(['publicFilteringCriteria'], newPublicFilteringCriteria)
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: `编辑 ${record.name} 公共筛选条件`,
              width: "500px",
            }}
            trigger={<a
              key="eidit"
              onClick={() => {
                publicFilteringCriteriaEditForm.resetFields()
                publicFilteringCriteriaEditForm.setFieldsValue(record)
              }}
            >
              编辑
            </a>}
            columns={publicFilteringCriteriaColumns as any}
          />,
          <Popconfirm
            key="del"
            title="删除"
            description={<>
              <p>确认删除 <b>{record?.name}</b> ?</p>
            </>}
            onConfirm={async () => {
              const publicFilteringCriteria = (form.getFieldsValue()?.publicFilteringCriteria || [])?.filter((item: any) => {
                return item?.key !== record?.key
              })
              form.setFieldValue(['publicFilteringCriteria'], publicFilteringCriteria)
              return true
            }}
            okText="是"
            cancelText="否"
          >
            <a
              key="del"
            >
              删除
            </a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const CustomCompanyBannerTable = (props: any) => {
    return <DragSortTable
      columns={companyBannerColumns}
      rowKey="key"
      search={false}
      pagination={false}
      dataSource={props?.value}
      onChange={props?.onChange}
      dragSortKey="sort"
      onDragSortEnd={(
        beforeIndex: number,
        afterIndex: number,
        newDataSource: any,
      ) => {
        // console.log('排序后的数据', newDataSource);
        // message.success('修改列表排序成功');
        form.setFieldValue(['company', 'banner'], newDataSource)
      }}
      toolBarRender={false}
      editable={{}}
    />
  }

  const CustomCompanyCertificateTable = (props: any) => {
    return <DragSortTable
      columns={companyCertificateColumns}
      rowKey="key"
      search={false}
      pagination={false}
      dataSource={props?.value}
      onChange={props?.onChange}
      dragSortKey="sort"
      onDragSortEnd={(
        beforeIndex: number,
        afterIndex: number,
        newDataSource: any,
      ) => {
        // console.log('排序后的数据', newDataSource);
        // message.success('修改列表排序成功');
        form.setFieldValue(['company', 'certificate'], newDataSource)
      }}
      toolBarRender={false}
      editable={{}}
    />
  }

  const CustomPublicFilteringCriteriaTable = (props: any) => {
    return <DragSortTable
      columns={publicFilteringCriteriaColumns}
      rowKey="key"
      search={false}
      pagination={false}
      dataSource={props?.value}
      onChange={props?.onChange}
      dragSortKey="sort"
      onDragSortEnd={(
        beforeIndex: number,
        afterIndex: number,
        newDataSource: any,
      ) => {
        // console.log('排序后的数据', newDataSource);
        // message.success('修改列表排序成功');
        form.setFieldValue(['publicFilteringCriteria'], newDataSource)
      }}
      toolBarRender={false}
      editable={{}}
    />
  }

  return (
    <ProForm
      layout="vertical"
      form={form}
      submitter={{
        render: (props, dom) => {
          return (
            <FooterToolbar>
              {/*{getErrorInfo(error)}*/}
              {dom}
            </FooterToolbar>
          );
        },
      }}
      initialValues={{}}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      // onValuesChange={(values) => {
      //   console.log(values)
      // }}
    >
      <PageContainer content="公共设置常用于对通用的功能设置">
        <Card title="公司信息" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'公司名称'}
                name={['company', "companyName"]}
                rules={[
                  {
                    message: '请输入公司名称',
                  },
                ]}
                placeholder="请输入公司名称"
              />
            </Col>
            <Col lg={24} md={24} sm={24}>
              <Row gutter={16}>
                <Col lg={6} md={6} sm={24}>
                  <Form.Item label={'公司logo'}
                             name={['company', "logoUrl"]}
                  >
                    <CustomImgUpload/>
                  </Form.Item>
                </Col>

              </Row>
            </Col>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'公司简称'}
                name={['company', "companyAbbreviation"]}
                rules={[
                  {
                    message: '请输入公司简称',
                  },
                ]}
                placeholder="请输入公司简称"
              />
            </Col>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'公司地址'}
                name={['company', "address"]}
                rules={[
                  {
                    message: '请输入公司地址',
                  },
                ]}
                placeholder="请输入公司地址"
              />
            </Col>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'公司联系电话'}
                name={['company', "contactPhone"]}
                rules={[
                  {
                    message: '请输入公司联系电话',
                  },
                ]}
                placeholder="请输入公司联系电话"
              />
            </Col>
            <Col lg={6} md={12} sm={24}></Col>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'公司传真'}
                name={['company', "fax"]}
                rules={[
                  {
                    message: '请输入公司传真',
                  },
                ]}
                placeholder="请输入公司传真"
              />
            </Col>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'公司邮编'}
                name={['company', "postalCode"]}
                rules={[
                  {
                    message: '请输入公司邮编',
                  },
                ]}
                placeholder="请输入公司邮编"
              />
            </Col>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'公司Email'}
                name={['company', "email"]}
                rules={[
                  {
                    message: '请输入公司Email',
                  },
                ]}
                placeholder="请输入公司Email"
              />
            </Col><Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'公司Web'}
                name={['company', "website"]}
                rules={[
                  {
                    message: '请输入公司Web',
                  },
                ]}
                placeholder="请输入公司Web"
              />
            </Col>
            <Col lg={24} md={24} sm={24}>
              <ProFormTextArea
                label={'公司概述'}
                name={['company', "companyOverview"]}
                rules={[
                  {
                    message: '请输入公司概述',
                  },
                ]}
                placeholder="请输入公司概述"
              />
            </Col>
            <Col lg={24} md={24} sm={24}>
              <Form.Item
                label={'公司简介(中文)'}
                name={['company', "introduction"]}
                // name={['company', "introduction_chinese"]}
                rules={[
                  {
                    message: '请输入公司简介',
                  },
                ]}>
                <CustomEditor/>
              </Form.Item>
            </Col>
            <Col lg={24} md={24} sm={24}>
              <Form.Item
                label={'公司简介(英文)'}
                name={['company', "introduction_english"]}
                rules={[
                  {
                    message: '请输入公司简介',
                  },
                ]}>
                <CustomEditor/>
              </Form.Item>
            </Col>
          </Row>
        </Card>

        <Card title="公司简介轮播" className={styles.card} bordered={false}>
          <BetaSchemaForm<any>
            key="primary"
            form={companyBannerAddForm}
            layoutType={'ModalForm'}
            onFinish={async (values) => {
              const companyBanner = form.getFieldsValue()?.company?.banner || []
              companyBanner.push({
                ...values,
                key: companyBanner?.length + 1 || 0,
              })
              form.setFieldValue(['company', 'banner'], [...companyBanner])
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: "新增公司简介轮播",
              width: "500px",
            }}
            trigger={<Button style={{marginBottom: 20}} onClick={() => {
              const companyBanner = form.getFieldsValue()?.company?.banner || []
              companyBannerAddForm.setFieldValue('sort', companyBanner?.length || 0)
            }}>新增</Button>}
            columns={companyBannerColumns as any}
          />
          <ProForm.Item name={['company', 'banner']}>
            <CustomCompanyBannerTable/>
          </ProForm.Item>
        </Card>

        <Card title="公司荣誉资质" className={styles.card} bordered={false}>
          <BetaSchemaForm<any>
            key="primary"
            form={companyCertificateAddForm}
            layoutType={'ModalForm'}
            onFinish={async (values) => {
              const companyCertificate = form.getFieldsValue()?.company?.certificate || []
              companyCertificate.push({
                ...values,
                key: companyCertificate?.length + 1 || 0,
              })
              form.setFieldValue(['company', 'certificate'], [...companyCertificate])
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: "新增公司荣誉资质",
              width: "500px",
            }}
            trigger={<Button style={{marginBottom: 20}} onClick={() => {
              const companyCertificate = form.getFieldsValue()?.company?.certificate || []
              companyCertificateAddForm.setFieldValue('sort', companyCertificate?.length || 0)
            }}>新增</Button>}
            columns={companyCertificateColumns as any}
          />
          <ProForm.Item name={['company', 'certificate']}>
            <CustomCompanyCertificateTable/>
          </ProForm.Item>
        </Card>

        <Card title="产品设置" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormSwitch
                label={'隐藏没有附件的产品'}
                name={['product', "hideWithoutFile"]}
                unCheckedChildren={'否'}
                checkedChildren={'是'}
              />
            </Col>
          </Row>
        </Card>

        <Card title="公共筛选条件" className={styles.card} bordered={false}>
          <BetaSchemaForm<any>
            key="primary"
            form={publicFilteringCriteriaAddForm}
            layoutType={'ModalForm'}
            onFinish={async (values) => {
              const publicFilteringCriteria = form.getFieldsValue()?.publicFilteringCriteria || []
              publicFilteringCriteria.push({
                ...values,
                key: publicFilteringCriteria?.length + 1 || 0,
              })
              form.setFieldValue(['publicFilteringCriteria'], [...publicFilteringCriteria])
              return true
            }}
            modalProps={{
              destroyOnClose: true,
              title: "新增公共筛选条件",
              width: "500px",
            }}
            trigger={<Button style={{marginBottom: 20}} onClick={() => {
              const publicFilteringCriteria = form.getFieldsValue()?.publicFilteringCriteria || []
              publicFilteringCriteriaAddForm.setFieldValue('sort', publicFilteringCriteria?.length || 0)
            }}>新增</Button>}
            columns={publicFilteringCriteriaColumns as any}
          />
          <ProForm.Item name={['publicFilteringCriteria']}>
            <CustomPublicFilteringCriteriaTable/>
          </ProForm.Item>
        </Card>
      </PageContainer>
    </ProForm>
  );
};
export default AdvancedForm;
